<template>
  <div class="home">
    <div class="home-header">
      <h1>📸 截图工具</h1>
      <p class="subtitle">功能强大的截图标注工具，支持 OCR 文字识别</p>
    </div>

    <div class="home-content">
      <div class="feature-section">
        <h2>✨ 功能特性</h2>
        <div class="features-grid">
          <div class="feature-card">
            <div class="feature-icon">⌨️</div>
            <h3>全局快捷键</h3>
            <p>按 <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>A</kbd> 快速截图</p>
          </div>

          <div class="feature-card">
            <div class="feature-icon">🎨</div>
            <h3>丰富标注</h3>
            <p>矩形、箭头、文字、马赛克、序号、高亮等多种标注工具</p>
          </div>

          <div class="feature-card">
            <div class="feature-icon">🔍</div>
            <h3>OCR 识别</h3>
            <p>支持中英文 OCR 文字识别，快速提取图片文字</p>
          </div>

          <div class="feature-card">
            <div class="feature-icon">💾</div>
            <h3>多种保存</h3>
            <p>支持保存到文件、复制到剪贴板、自动保存历史</p>
          </div>

          <div class="feature-card">
            <div class="feature-icon">↩️</div>
            <h3>撤销重做</h3>
            <p>支持无限次撤销和重做操作</p>
          </div>

          <div class="feature-card">
            <div class="feature-icon">🖱️</div>
            <h3>系统托盘</h3>
            <p>最小化到系统托盘，随时待命</p>
          </div>
        </div>
      </div>

      <div class="action-section">
        <button class="start-button" @click="startScreenshot">
          开始截图
        </button>
        <button class="history-button" @click="toggleHistory">
          查看历史
        </button>
        <button 
          class="ocr-button" 
          @click="initOCR"
          :disabled="ocrStatus === 'loading'"
        >
          {{ ocrButtonText }}
        </button>
        <button class="settings-button" @click="goToSettings">
          ⚙️ 设置
        </button>
      </div>

      <!-- OCR 初始化进度提示 -->
      <div v-if="ocrStatus === 'loading'" class="ocr-progress">
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: ocrProgress + '%' }"></div>
        </div>
        <p class="progress-text">{{ ocrStatusText }}</p>
      </div>

      <div class="shortcuts-section">
        <h2>⌨️ 快捷键说明</h2>
        <div class="shortcuts-list">
          <div class="shortcut-item">
            <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>A</kbd>
            <span>开始截图</span>
          </div>
          <div class="shortcut-item">
            <kbd>ESC</kbd>
            <span>取消截图</span>
          </div>
          <div class="shortcut-item">
            <kbd>Enter</kbd>
            <span>保存截图</span>
          </div>
          <div class="shortcut-item">
            <kbd>Ctrl</kbd> + <kbd>Z</kbd>
            <span>撤销</span>
          </div>
          <div class="shortcut-item">
            <kbd>Ctrl</kbd> + <kbd>Y</kbd>
            <span>重做</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 历史记录面板 -->
    <transition name="slide">
      <div v-if="showHistory" class="history-panel">
        <ScreenshotHistory />
        <button class="close-history" @click="toggleHistory">关闭</button>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ScreenshotHistory from '@/components/Screenshot/ScreenshotHistory.vue'
import { ocrService } from '@/utils/screenshot/ocrService'

const router = useRouter()

const showHistory = ref(false)
const ocrStatus = ref<'idle' | 'loading' | 'ready' | 'error'>('idle')
const ocrProgress = ref(0)
const ocrStatusText = ref('')

const ocrButtonText = computed(() => {
  switch (ocrStatus.value) {
    case 'idle':
      return '🔍 初始化 OCR'
    case 'loading':
      return '⏳ 下载中...'
    case 'ready':
      return '✅ OCR 已就绪'
    case 'error':
      return '❌ 初始化失败'
    default:
      return '🔍 初始化 OCR'
  }
})

const startScreenshot = () => {
  if (window.electronAPI) {
    window.electronAPI.takeScreenshot()
  } else {
    alert('请在 Electron 环境中运行此应用')
  }
}

const toggleHistory = () => {
  showHistory.value = !showHistory.value
}

const goToSettings = () => {
  router.push('/settings')
}

const initOCR = async () => {
  if (ocrStatus.value === 'ready') {
    alert('OCR 已经初始化完成，可以直接使用！')
    return
  }

  if (ocrStatus.value === 'loading') {
    return
  }

  try {
    ocrStatus.value = 'loading'
    ocrProgress.value = 0
    ocrStatusText.value = '正在下载中文语言包（约 25MB）...'

    // 模拟进度（因为 tesseract.js 的 logger 不提供准确的下载进度）
    const progressInterval = setInterval(() => {
      if (ocrProgress.value < 90) {
        ocrProgress.value += 1
      }
    }, 200)

    await ocrService.preload()

    clearInterval(progressInterval)
    ocrProgress.value = 100
    ocrStatusText.value = 'OCR 初始化完成！'
    ocrStatus.value = 'ready'

    setTimeout(() => {
      alert('OCR 已就绪！\n\n现在可以在截图时使用 OCR 功能识别文字了。\n首次识别会更快速！')
    }, 500)
  } catch (error) {
    ocrStatus.value = 'error'
    ocrStatusText.value = '初始化失败，请检查网络连接'
    console.error('OCR 初始化失败:', error)
    alert('OCR 初始化失败，请检查网络连接后重试')
  }
}

// 显示 OCR 状态
const showOCRStatus = () => {
  let statusMsg = ''
  switch (ocrStatus.value) {
    case 'idle':
      statusMsg = 'OCR 未初始化\n\n点击"初始化 OCR"按钮或从菜单"工具 -> 初始化 OCR"开始下载语言包'
      break
    case 'loading':
      statusMsg = `OCR 正在下载中...\n\n进度：${ocrProgress.value}%\n状态：${ocrStatusText.value}`
      break
    case 'ready':
      statusMsg = 'OCR 已就绪！✅\n\n语言包已下载完成，可以正常使用 OCR 功能'
      break
    case 'error':
      statusMsg = 'OCR 初始化失败 ❌\n\n请检查网络连接后重试'
      break
  }
  alert(`OCR 状态\n\n${statusMsg}`)
}

// 检查 OCR 是否已经初始化
onMounted(() => {
  if (ocrService.isReady()) {
    ocrStatus.value = 'ready'
  }

  // 监听菜单事件
  if (window.electronAPI) {
    window.electronAPI.onShowOCRStatus?.(() => {
      showOCRStatus()
    })
    window.electronAPI.onInitOCR?.(() => {
      initOCR()
    })
  }
})
</script>

<style scoped>
.home {
  min-height: 100vh;
  height: 100vh;
  overflow-y: auto; /* 允许主页滚动 */
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-attachment: fixed; /* 固定背景，减少重绘 */
  color: white;
  padding: 40px;
  position: relative;
  /* 启用硬件加速 */
  transform: translateZ(0);
  -webkit-overflow-scrolling: touch; /* 移动端流畅滚动 */
}

.home-header {
  text-align: center;
  margin-bottom: 60px;
}

.home-header h1 {
  font-size: 48px;
  margin: 0 0 16px 0;
  font-weight: 700;
}

.subtitle {
  font-size: 18px;
  opacity: 0.9;
  margin: 0;
}

.home-content {
  max-width: 1200px;
  margin: 0 auto;
}

.feature-section {
  margin-bottom: 60px;
}

.feature-section h2 {
  font-size: 32px;
  margin: 0 0 32px 0;
  text-align: center;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.feature-card {
  background-color: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 32px;
  text-align: center;
  transition: transform 0.3s ease, background-color 0.3s ease;
  /* 启用硬件加速，减少重绘 */
  will-change: transform;
  transform: translateZ(0);
}

.feature-card:hover {
  transform: translateY(-8px) translateZ(0);
  background-color: rgba(255, 255, 255, 0.15);
}

.feature-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.feature-card h3 {
  font-size: 20px;
  margin: 0 0 12px 0;
}

.feature-card p {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
  line-height: 1.6;
}

.action-section {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-bottom: 60px;
}

.start-button,
.history-button,
.ocr-button {
  padding: 16px 48px;
  font-size: 18px;
  font-weight: 600;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  transition: transform 0.3s ease, background-color 0.3s ease, box-shadow 0.3s ease;
  /* 硬件加速 */
  will-change: transform;
  transform: translateZ(0);
}

.start-button {
  background-color: white;
  color: #667eea;
}

.start-button:hover {
  transform: scale(1.05) translateZ(0);
  box-shadow: 0 8px 24px rgba(255, 255, 255, 0.3);
}

.history-button {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid white;
}

.history-button:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: scale(1.05) translateZ(0);
}

.ocr-button {
  background-color: rgba(255, 165, 0, 0.9);
  color: white;
}

.ocr-button:hover:not(:disabled) {
  background-color: rgba(255, 140, 0, 1);
  transform: scale(1.05) translateZ(0);
}

.ocr-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.settings-button {
  background-color: rgba(158, 158, 158, 0.9);
  color: white;
  border: none;
}

.settings-button:hover {
  background-color: rgba(117, 117, 117, 1);
  transform: scale(1.05);
}

.ocr-progress {
  max-width: 600px;
  margin: 0 auto 40px;
  padding: 24px;
  background-color: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  text-align: center;
  /* 硬件加速 */
  transform: translateZ(0);
}

.progress-bar {
  width: 100%;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 12px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4caf50, #8bc34a);
  transition: width 0.3s ease;
  border-radius: 12px;
}

.progress-text {
  font-size: 16px;
  margin: 0;
  color: white;
}

.shortcuts-section {
  background-color: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 40px;
  /* 硬件加速 */
  transform: translateZ(0);
}

.shortcuts-section h2 {
  font-size: 28px;
  margin: 0 0 24px 0;
  text-align: center;
}

.shortcuts-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.shortcut-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.shortcut-item span {
  flex: 1;
}

kbd {
  padding: 4px 8px;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  font-family: monospace;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.history-panel {
  position: fixed;
  right: 0;
  top: 0;
  height: 100vh;
  background-color: white;
  box-shadow: -4px 0 12px rgba(0, 0, 0, 0.2);
  z-index: 1000;
}

.close-history {
  position: absolute;
  top: 16px;
  right: 16px;
  padding: 8px 16px;
  background-color: #f44336;
  border: none;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  transition: background-color 0.2s;
}

.close-history:hover {
  background-color: #d32f2f;
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  transform: translateX(100%);
}
</style>

